/**
 * 验证码生成工具
 */

// 生成随机验证码
export function generateCaptcha(length = 4, type = 'alphanumeric') {
  let chars = ''

  switch (type) {
    case 'numeric':
      chars = '0123456789'
      break
    case 'alphabetic':
      chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      break
    case 'alphanumeric':
    default:
      chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
      break
  }

  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 生成验证码图片的SVG
export function generateCaptchaSVG(code) {
  const width = 100
  const height = 40

  // 生成随机颜色
  const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']
  const bgColor = '#f5f7fa'
  const textColor = colors[Math.floor(Math.random() * colors.length)]

  // 生成干扰线
  const lines = []
  for (let i = 0; i < 3; i++) {
    const x1 = Math.random() * width
    const y1 = Math.random() * height
    const x2 = Math.random() * width
    const y2 = Math.random() * height
    const color = colors[Math.floor(Math.random() * colors.length)]
    lines.push(`<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1" opacity="0.6"/>`)
  }

  // 生成干扰点
  const dots = []
  for (let i = 0; i < 20; i++) {
    const x = Math.random() * width
    const y = Math.random() * height
    const color = colors[Math.floor(Math.random() * colors.length)]
    dots.push(`<circle cx="${x}" cy="${y}" r="1" fill="${color}" opacity="0.8"/>`)
  }

  // 生成文字
  const fontSize = 18
  const letterSpacing = 15
  const startX = 10
  const startY = 25

  const texts = code.split('').map((char, index) => {
    const x = startX + index * letterSpacing
    const y = startY + (Math.random() - 0.5) * 10
    const rotation = (Math.random() - 0.5) * 30
    return `<text x="${x}" y="${y}" font-family="Arial, sans-serif" font-size="${fontSize}" fill="${textColor}" transform="rotate(${rotation} ${x} ${y})">${char}</text>`
  }).join('')

  const svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <rect width="${width}" height="${height}" fill="${bgColor}"/>
      ${lines.join('')}
      ${dots.join('')}
      ${texts}
    </svg>
  `

  return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)))
}

// 生成验证码数据URL
export function generateCaptchaDataURL(length = 4, type = 'alphanumeric') {
  const code = generateCaptcha(length, type)
  const svgDataURL = generateCaptchaSVG(code)
  return {
    code,
    dataURL: svgDataURL
  }
}

// 验证验证码
export function validateCaptcha(input, correctCode, caseSensitive = false) {
  console.log(input, correctCode)
  if (caseSensitive) {
    return input === correctCode
  } else {
    return input.toUpperCase() === correctCode.toUpperCase()
  }
}
